package com.lagou.codeservice.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.lagou.codeservice.feign.RemoteEmailService;
import com.lagou.common.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2021/1/14
 */
@RestController
public class CodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteEmailService emailService;

    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable("email")String email)
    {
        Random random = new Random();
        int i = random.nextInt(8999);
        String code = 1000+i+"";
        DateTime dateTime = DateUtil.dateSecond();
        dateTime=DateUtil.offset(dateTime, DateField.MINUTE,5);
        Boolean r = emailService.email(email, code);
        if(r){
            User user = new User(email,null,code,dateTime,null);
            redisTemplate.opsForValue().set(email,user);
        }
        return r;
    }

    @GetMapping("/validate/{email}/{code}")
    public Integer email(@PathVariable("email")String email,@PathVariable("code")String code)
    {
        User user = (User)redisTemplate.opsForValue().get(email);
        if(user==null)
        {
            return 1;
        }
        String checkcode = user.getCheckcode();
        DateTime expireTime = user.getExpireTime();
        if(!StringUtils.equals(checkcode,code))
        {
            return 1;
        }
        if(DateUtil.compare(DateUtil.dateSecond(),expireTime)>0)
        {
            return 2;
        }
        return 0;
    }
}
